package com.overlord.im.connector.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @author wuwei
 * @className OsUtils
 * @description
 * @date 2020/5/28 10:53
 **/
public class OsUtils {
    private static final Logger logger = LoggerFactory.getLogger(OsUtils.class);

    private static String pid;

    private static String hostIp;

    private static final String LOCAL_BACK_IP = "127.0.0.1";

    public static String getCurrentPid() {
        if (StringUtils.isBlank(pid)) {
            try {
                String name = ManagementFactory.getRuntimeMXBean().getName();
                pid = StringUtils.split(name, "@")[0];
            } catch (Exception e) {
                logger.error("获取当前线程名失败", e);
            }
        }
        return pid;
    }

    public static String getHostName() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            return localHost.getHostName();
        } catch (UnknownHostException e) {
            throw new RuntimeException("获取hostname失败");
        }
    }

    public static String getHostIp() {
        try {
            if (StringUtils.isBlank(hostIp)) {
                InetAddress localHost = InetAddress.getLocalHost();
                String ip = localHost.getHostAddress();
                if (ip != null && LOCAL_BACK_IP.equals(ip)) {
                    logger.warn("从host获取ip得到127.0.0.1将从网卡获取......");
                    return getRealHostIp();
                }
                hostIp = ip;
            }
            return hostIp;
        } catch (Exception e) {
            throw new RuntimeException("获取本机ip失败", e);
        }
    }

    public static String getRealHostIp() {
        if (StringUtils.isNotBlank(hostIp)) {
            return hostIp;
        }
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            if (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                Enumeration<InetAddress> e2 = ni.getInetAddresses();

                while (e2.hasMoreElements()) {
                    InetAddress ia = e2.nextElement();
                    if (ia.isSiteLocalAddress()) {
                        hostIp = ia.getHostAddress();

                        break;
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException("获取本机ip失败", e);
        }
        return hostIp;
    }
}
